// use mootools ammend basic javascript function
require('mootools');
var path = require('path');
var winston = require('winston');// our log writer
// write log to file not only to console, using local time
winston.add(winston.transports.File, { filename: path.join(__dirname, "log", "wephotosite.log"), timestamp: function(){ return new Date().toTimeString()}});

var express = require('express');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var logger = require('morgan');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var mysql = require('mysql');
var request = require("request");
var dbConfig = require('./lib/config.js').db;
var pool = mysql.createPool(Object.append({}, {
	connectionLimit: 480
}, dbConfig));
var errorHandler = require('errorhandler');
var api = require('./api/index');
var app = express();
var favicon = require('serve-favicon');
// configure express server
app.set('env', 'development');
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 8989);
app.set('trust proxy', true);
app.set('case sensitive routing', true);
app.set('strict routing', false);

app.use(logger('combined'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser("wephoto_cookie"));
/*
app.use(session({
  secret: 'wephoto_session',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));
*/

app.use(favicon(__dirname + '/favicon.ico'));
app.use(express.static(path.join(__dirname + '/public')));
app.use('/assets', express.static(path.join(__dirname + '/assets')));
app.use('/vendor', express.static(path.join(__dirname + '/bower_components')));

if(app.get('env') === 'development'){
	app.set('view cache', false);
	app.set('etag', false);
}
app.get('/disney', function(req, res){ 
	res.render('other/d');
});
app.get('/t4g', function(req, res){ 
	var page = req.query.p;
	res.render('other/t4g-' + page);
});
app.get('/map', function(req, res){
	var d = {};
	['lon','lat','title','address'].forEach(function(v,k){
		if(req.query[v]) d[v] = req.query[v];
	});
	d.lon = d.lon || 116.397428;
	d.lat = d.lat || 39.90923;
	res.render('other/map', {
		data: d
	});	
});
app.get('/qrcode', function(req, res){
	res.render('addons/qrcode');	
});
app.get('/roland', function(req, res){
	res.render('addons/roland');
});
/** 
 * @url detect visitor's userAgent
 */
app.get('/userAgent', function(req, res){
	res.send(req.header('user-agent'));
});

app.post('/lucky/:eventId', function(req, res, next){ 
	api.lucky(pool, req, res, next);
});
/**
 * @eventId nubmer
 * 
 */
app.get('/ld/:eventId', function(req, res, next){
	api.luckydraw(pool, req, res, next);
});	

app.get('/photowall/:eventId', function(req, res){
	var eventId = req.params.eventId;
	var pathToPage = path.join(__dirname, 'templates/pw', eventId + '.ejs');
	fs.exists(pathToPage, function(exists){
		if(exists){
			res.render('pw/' + eventId, {eventId: eventId});
		}else{
			res.render('pw/index');
		}
	});
});
/**
 * @url entry of wesmile production
 *
 * @params {nubmer} eventId
 */
app.get('/ws-prod/:eventId', function(req, res){
	var eventId = req.params.eventId;
	var pathToPage = path.join(__dirname, 'templates/ws-prod', eventId + '.ejs');
	fs.exists(pathToPage, function(exists){
		if(exists){
			res.render('ws-prod/' + eventId, {eventId: eventId});
		}else{
			res.render('ws-prod/index');
		}
	});
});
/**
 * @url entry of wesmile test
 *
 * @params {nubmer} eventId
 */
app.get('/wesmile/:eventId', function(req, res){
	var eventId = req.params.eventId;
	var pathToPage = path.join(__dirname, 'templates/wesmile', eventId + '.ejs');
	fs.exists(pathToPage, function(exists){
		if(exists){
			res.render('wesmile/' + eventId, {eventId: eventId});
		}else{
			res.render('wesmile/index');
		}
	});
});
/**
 * @proxy for wesmile
 *
 */
app.get('/wesmileProxy', function(req, res){
	var api = req.query.api;
	var data = req.query.data;
	api = decodeURIComponent(api);
	request.get(api+"?"+data, function(err, response, body){
		if(err){
			winston.error(err);
		}else if(response.statusCode == 200){
			res.send(body);
		}else{
			res.end();
		}
	});
});

app.get('/sendfile/:archive', function(req, res){
	var archive = path.join(__dirname, 'public', 'archives', req.params.archive);
	res.sendFile(archive);
});

app.get('/d', function(req, res){
	res.render("other/detect");
});
app.get('/event', function(req, res){
  	res.render("index");
});
/**
 * @url wephoto entry
 *
 * http://wephoto.we-product.com/event/1
 */ 
app.get('/event/:eventId', function(req, res){
	var eventId = req.params.eventId + "";
	var pathToPage = path.join(__dirname, 'templates', eventId + '.ejs');
	fs.exists(pathToPage,  function(exists){
		if(exists){
			res.render(eventId);
		}else{
			res.render('index');
		}
	});
		
});
/**
 * @url show wephoto data 
 */
app.get('/showdata', function(req, res){
	fs.readFileAsync(path.join(__dirname, 'templates/addons/wephotodata.html'))
		.then(function(d){
			res.send(d.toString());

		})
		.catch(function(err){
			winston.error(err);
			res.end(404);
		});
});
app.get('/sendemail/roland', function(req, res, next){
	api.sendEmailRoland(pool, req, res, next);
});
/**
 * @url check printed photos
 */
app.get('/checkprint', function(req, res){
	res.render('addons/checkprint');
});

/**
 * @url manuplate on the photo states 
 */
app.get('/photostate', function(req, res){
	res.render('addons/showOrHide');
});
/**
 * @url the share page address, also is the content of qrcode 
 *
 * http://test.we-product.com/share/fKrSwUubyp
 */
app.get('/share/:uriMap', function(req, res, next){
	api.getSharePage(pool, req, res, next);
});
/**
 * @api get dynamic photo list for an event
 * 
 * http://wephoto.we-product.com/photolist/1?startTime=0
 */ 
app.get('/photolist/:eventId', function(req, res, next){
	api.getPhotolist(pool, req, res, next);
});
/**
 * @api generate qrcode 
 *
 * http://wephoto.we-product.com/qr/the-content-of-the-qrcode
 */
app.get('/qr/:content', function(req, res, next){
	api.drawQrcode(req, res, next);
});
/**
 * @api border to qrcode 
 *
 * http://wephoto.we-product.com/bqr/the-content-of-the-qrcode
 */
app.get('/bqr/:content', function(req, res, next){
	api.borderedQr(req, res, next);
});
/**
 * @api get a list of photos to be print
 *
 * http://wephoto.we-product.com/printlist/1
 */
app.get('/printlist/:eventId', function(req, res, next){
	api.getPrintlist(pool, req, res, next);
});
/**
 * @api record photos that been chosen in db
 *
 * post http://wephoto.we-product.com/print/1
 * data: {array} [printItems] [{photoId:1,copies:1},{photoId:2,copies:1}] 
 */
app.post('/print/:eventId', function(req, res, next){
	api.insertPrint(pool, req, res, next);
});
/**
 * @api generate uriMap when wephoto goes to step 2
 *
 * post http://wephoto.we-product.com/share/1
 * data: {string} [shareContent] '^(1|2)$'
 */
app.post('/share/:eventId', function(req, res, next){
	api.insertShare(pool, req, res, next);
});
/**
 * @api hide or show all photos of an event or by photo id
 *
 * http://wephoto.we-product.com/photoupdate/hide?photoId=1 or
 * http://wephoto.we-product.com/photoupdate/show?eventId=1
 */
app.get('/photoUpdate/:action', function(req, res, next){
	api.photoUpdate(pool, req, res, next);
});
/**
 * @api get print info for an event
 *
 * http://wephoto.we-product.com/printInfo/1?type=[all|printed|unprinted]
 */
app.get('/printInfo/:eventId', function(req, res, next){
	api.printInfo(pool, req, res, next);
});
/**
 * @api get share info for an event
 *
 * http://wephoto.we-product.com/shareInfo/1
 */
app.get('/shareInfo/:eventId', function(req, res, next){
	api.shareInfo(pool, req, res, next);
});
/**
 * @api send email for an event
 * 
 * post http://test.we-product.com/sendEmail/fKrSwUubyp
 *
 */
app.post('/sendEmail/:uriMap', function(req, res, next){
	api.sendEmail(pool, req, res, next);
});
/**
 * @api get event data for an event
 *
 * http://wephoto.we-product.com/eventData/1
 */
app.get('/eventData/:eventId', function(req, res, next){
	api.getEventData(pool, req, res, next);
});

app.use(errorHandler());



app.listen(app.get('port'), function(){
	console.log('server is listening on port: ' + app.get('port'));
});
